param (
    [string]$SDK_PATH = "E:/OpenHarmony/Sdk/15",
    [ValidateSet('arm', 'aarch64', 'x86_64')]
    [string]$ARCH = "arm"
)

# 设置OpenHarmony SDK路径
$OH_SDK_HOME = $SDK_PATH
$CLANG = "$OH_SDK_HOME/native/llvm/bin/clang++.exe"
$SYSROOT = "$OH_SDK_HOME/native/sysroot"
$TARGET = "arm-linux-ohos"
$GCC_TOOLCHAIN = "$OH_SDK_HOME/native/llvm"

# 根据架构设置目标平台
switch ($ARCH) {
    "arm" { $TARGET = "arm-linux-ohos" }
    "aarch64" { $TARGET = "aarch64-linux-ohos" }
    "x86_64" { $TARGET = "x86_64-linux-ohos" }
}

Write-Host "Building for architecture: $ARCH"
Write-Host "Using OpenHarmony SDK: $OH_SDK_HOME"

# 添加库路径
$LIB_PATHS = @(
    "-L`"$SYSROOT/usr/lib`"",
    "-L`"$SYSROOT/usr/lib/$TARGET`"",
    "-L`"$OH_SDK_HOME/native/share/libs`"",
    "-L`"$OH_SDK_HOME/native/share/libs/multimedia`""
)

# 编译参数
$INCLUDES = @(
    "-I`"$SYSROOT/usr/include`"",
    "-I`"$OH_SDK_HOME/native/share/include`""
)
$DEFINES = "-DOHOS_PLATFORM"
$FLAGS = @(
    "--target=$TARGET",
    "--gcc-toolchain=$GCC_TOOLCHAIN",
    "--sysroot=$SYSROOT",
    "-fPIC",
    "-Wall"
)

# 链接参数
$LINK_FLAGS = $LIB_PATHS + @(
    "-lnative_avscreen_capture",
    "-lnative_buffer",
    "-lnative_media_core",
    "-lnative_media_avcencinfo",
    "-lnative_media_vdec",
    "-lnative_media_venc",
    "-lnative_media_codecbase",
    "-lhilog_ndk.z",
    "-lc++",
    "-lc",
    "-ldl"
)

# 检查库文件是否存在
Write-Host "Checking library paths..."
foreach ($path in $LIB_PATHS) {
    $libPath = $path -replace "^-L`"(.+)`"$", '$1'
    if (Test-Path $libPath) {
        Write-Host "Found library path: $libPath"
        Get-ChildItem $libPath -Filter "*multimedia*.so" | ForEach-Object {
            Write-Host "  Found library: $($_.Name)"
        }
    } else {
        Write-Host "Warning: Library path not found: $libPath"
    }
}

# 编译源文件
Write-Host "Compiling screenrecord.cpp..."
$CompileArgs = $FLAGS + $DEFINES + $INCLUDES + @("-c", "screenrecord.cpp", "-o", "screenrecord.o")
& $CLANG $CompileArgs

if ($LASTEXITCODE -ne 0) {
    Write-Error "Compilation failed!"
    exit 1
}

# 链接可执行文件
Write-Host "Linking executable..."
$LinkArgs = $FLAGS + @("screenrecord.o") + $LINK_FLAGS + @("-o", "screenrecord", "-v")
Write-Host "Link command: $CLANG $LinkArgs"
& $CLANG $LinkArgs

if ($LASTEXITCODE -ne 0) {
    Write-Error "Linking failed!"
    exit 1
}

Write-Host "Build completed successfully!" -ForegroundColor Green